package com.cysyz.mylib.jpadao;


import com.cysyz.mylib.dao.engine.ClassMetadata;
import com.cysyz.mylib.dao.engine.PersistenceEngine;
import com.cysyz.mylib.dao.engine.Query;
import com.cysyz.mylib.dao.engine.SQLQuery;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import java.io.Serializable;
import java.util.List;

public class PersistenceEngineJPA implements PersistenceEngine {

    @PersistenceContext
    protected EntityManager em;


    @Override
    public void persist(Object entity) {
        em.persist(entity);
    }

    @Override
    public void remove(Object entity) {
        em.remove(entity);
    }

    @Override
    public void removeByCollection(List list) {
        for (Object o : list) {
            em.remove(o);
        }
    }

    @Override
    public void merge(Object entity) {
        em.merge(entity);
    }

    @Override
    public <T> T get(Class<T> entityClass, Serializable entityID) {
        return em.find(entityClass, entityID);
    }

    @Override
    public <T> T getReference(Class<T> entityClass, Serializable entityID) {
        return em.getReference(entityClass, entityID);
    }

    @Override
    public Query createQuery(String ql) {
        return new QueryJPA(em.createQuery(ql));
    }

    @Override
    public SQLQuery createSQLQuery(String sql) {
        return new SQLQueryJPA(em.createNativeQuery(sql));
    }

    @Override
    public SQLQuery createSQLQuery(String sql, String mappingInfo) {
        return new SQLQueryJPA(em.createNativeQuery(sql, mappingInfo));
    }


    @Override
    public ClassMetadata getClassMetadata(Class entityClass) {
        return null;
    }

    public CriteriaBuilder getCriteriaBuilder() {
        return em.getCriteriaBuilder();
    }

    public TypedQuery createQuery(CriteriaQuery c) {

        return em.createQuery(c);
    }

    public CriteriaQueryJPA getCriteriaQuery(Class clazz) {
        return new CriteriaQueryJPA(clazz, em);
    }

}
